import { computed, reactive, ref } from 'vue';
import type { ComputedRef } from 'vue';
import { useRoute } from 'vue-router';
import { defineStore } from 'pinia';
import { useLoading } from '@sa/hooks';
import { SetupStoreId } from '@/enum';
import { useRouterPush } from '@/hooks/common/router';
import { fetchGetUserInfo, fetchLogin, fetchLogout } from '@/service/api';
import { sessionStg } from '@/utils/storage';
import { useRouteStore } from '../route';
import { useTabStore } from '../tab';
import { clearAuthStorage, getToken } from './shared';

export const useAuthStore = defineStore(SetupStoreId.Auth, () => {
  const route = useRoute();
  const routeStore = useRouteStore();
  const tabStore = useTabStore();
  const { toLogin, redirectFromLogin } = useRouterPush(false);
  const { loading: loginLoading, startLoading, endLoading } = useLoading();

  const token = ref(getToken());

  const userInfo: CommonApi.User.UserInfo = reactive({
    userId: '',
    userName: ''
  });

  /** 是否已登录 */
  const isLogin = computed(() => Boolean(token.value));

  /** 登录静态菜单权限 */
  const staticRoles: ComputedRef<string[]> = computed(() => {
    return [];
  });

  /** 重置权限 store */
  async function resetStore() {
    const authStore = useAuthStore();

    clearAuthStorage();

    authStore.$reset();

    resetTokenStg();

    if (!route.meta.constant) {
      await toLogin();
    }

    tabStore.cacheTabs();
    routeStore.resetStore();
  }

  /** 退出登录 */
  async function logout() {
    if (token.value) {
      await fetchLogout();
    }
    await resetStore();
  }

  /**
   * 登录
   *
   * @param params.userPhone 电话号
   * @param params.password 密码
   * @param [redirect=true] 是否重定向的到登录页，默认为 true. Default is `true`
   */
  async function login(params: LoginApi.LoginParams, redirect = true) {
    startLoading();

    const { data, error } = await fetchLogin(params);

    if (!error) {
      const pass = await loginByToken(data);

      if (pass) {
        await routeStore.initAuthRoute();

        await redirectFromLogin(redirect);

        // if (routeStore.isInitAuthRoute) {
        //   window.$notification?.success({
        //     title: '登录成功',
        //     content: `欢迎回来 ${userInfo.userName} !`,
        //     duration: 4500
        //   });
        // }
      }
    } else {
      resetStore();
    }

    endLoading();
  }

  /** 删除 token sessionStorage */
  function resetTokenStg() {
    sessionStg.remove('token');
    sessionStg.remove('refreshToken');
    sessionStg.remove('expiration');

    token.value = '';
  }

  /** 设置 token sessionStorage */
  function setTokenStg(data: LoginApi.Token) {
    sessionStg.set('token', data.accessToken);
    sessionStg.set('refreshToken', data.refreshToken);
    // 有效期时长（单位秒）
    sessionStg.set('expiration', data.expiration);
  }

  async function loginByToken(data: LoginApi.Token) {
    // 1. 存储在 sessionStorage 中，后续请求需要在请求头中使用它
    setTokenStg(data);

    // 2. 获取用户信息
    const pass = await getUserInfo();

    if (pass) {
      token.value = data.accessToken;

      return true;
    }

    return false;
  }

  async function getUserInfo() {
    const { data: info, error } = await fetchGetUserInfo();

    if (!error) {
      // 更新 store
      Object.assign(userInfo, info);

      return true;
    }

    return false;
  }

  async function initUserInfo() {
    const hasToken = getToken();

    if (hasToken) {
      await getUserInfo();

      // if (!pass) {
      //   resetStore();
      // }
    }
  }

  return {
    token,
    staticRoles,
    userInfo,
    isLogin,
    loginLoading,
    startLoading,
    endLoading,
    resetStore,
    login,
    initUserInfo,
    logout,
    resetTokenStg,
    setTokenStg
  };
});
